<template>
  <div class="container">
    <div class="containerEart">
      <p class="dialogTitle">次生灾害隐患评估</p>
      <div class="header">
        <span class="title">震情趋势：</span>
        <div class="icon">
              <svg-icon class-name="error-icon" icon-class="error" style="margin-right:10px" v-if="showIcon"/><span>{{titleOption}}</span>
        </div>
      </div>
      <div class="header">
        <span class="title">评估内容</span>
        <div>
          <el-radio-group v-model="ssdContent">
            <el-radio label="危险源分布图">危险源分布图</el-radio>
            <el-radio label="危害等级分布图">危害等级分布图</el-radio>
            <el-radio label="地震地质灾害隐患点分布图">地震地质灾害隐患点分布图</el-radio>
            <el-radio label="地质灾害统计">地质灾害统计</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAssess">
          <svg-icon class-name="assess-icon" icon-class="assess" /><span style="margin-left:10px">评估</span>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="openUpload" :disabled="!ssdContent">
          <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">成果上传</span>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="handleDownload">
          <svg-icon class-name="download-icon" icon-class="download" /><span style="margin-left:10px">批量下载</span>
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" @click="handleSubmit">
          <svg-icon class-name="submit-icon" icon-class="submit" /><span style="margin-left:10px">提交</span>
        </el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评估内容" align="center" prop="ssdContent" />
      <el-table-column label="生成时间" align="center" prop="ssdDate" />
      <el-table-column label="业务人员" align="center" prop="ssdPeople" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleDetil(scope.row)">查看</el-button>
          <el-button type="text" @click="handledel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 上传对话框 -->
    <el-dialog v-model="open" width="800px" :title="title">
      <p></p>
      <el-form ref="secondaryRef" :model="queryParams" :rules="rules" label-width="150px">
        <template v-if="ssdContent!='地质灾害统计'">
          <el-form-item label="图片" prop="ssdImageId">
            <image-upload ref="imageUpload" :limit="limit" v-model="queryParams.attach" />
          </el-form-item>
          <el-form-item label="标题" prop="ssdImageTitle">
            <el-input v-model="queryParams.ssdImageTitle" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="描述" prop="ssdDescribe">
            <el-input v-model="queryParams.ssdDescribe" type="textarea" maxlength="300" show-word-limit
              :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入描述" />
          </el-form-item>
        </template>
        <template v-else>
          <el-row>
            <el-col :span="24">
              <el-form-item label="按月统计" prop="ssdMouseFileId">
                <file-upload ref="ssdMouseFileRef" :limit="limit" :fileType="['xlsx']" :types="type1"
                  @uploadFile="uploadFile" @delFile="delFile" v-model="queryParams.mouseAttachment" />
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('地震地质灾害-按月统计模板.xlsx')">下载模板</el-link>
                <div style="width:100%">
                  <el-button type="primary" :disabled="disabledMonFile" @click="createExcleMon">生成图表</el-button>
                </div>
              </el-form-item>
              <template v-if="showMon">
                <table width="100%" height="100" border="1" cellspacing="0" cellpadding="0">
                  <tr>
                    <th colspan="2" rowspan="2">数量月份</th>
                    <th colspan="2">灾害总数</th>
                    <th colspan="2">滑坡灾害</th>
                    <th colspan="2">崩塌灾害</th>
                    <th colspan="2">泥石流灾害</th>
                    <th colspan="2">地面塌陷灾害</th>
                    <th colspan="2">地面沉降灾害</th>
                    <th colspan="2">地裂缝不稳定斜坡灾害</th>
                    <th colspan="2">其他灾害</th>
                  </tr>
                  <tr>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                    <th>数量</th>
                    <th>百分比</th>
                  </tr>
                  <tr v-for="(item,index) in monList" :key="index">
                    <template v-for="(val,ind) in item" :key="ind">
                      <td  v-if="ind==0" colspan="2"><span>{{val}}</span></td>
                      <td  v-if="ind!=0"><span>{{val}}</span></td>
                    </template>
                  </tr>
                </table>
                <div id="mainMonPic" style="width: 700px; height: 500px;padding-left: 100px;"></div>
                <p style="text-align: center;font-weight: bold;">月份</p>
              </template>
              <el-form-item label="按月统计标题" prop="ssdMonthTitle">
                <el-input v-model="queryParams.ssdMonthTitle" placeholder="请输入标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="区域统计" prop="ssdAreaFileId">
                <file-upload ref="ssdAreaFileRef" :limit="limit" :fileType="['xlsx']" :types="type2"
                  @uploadFile="uploadFile" @delFile="delFile" v-model="queryParams.areaAttachment" />
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('地震地质灾害-区域统计模板.xlsx')">下载模板</el-link>
                <div style="width:100%">
                  <el-button type="primary" :disabled="disabledAreaFile" @click="createExcleArea">生成图表</el-button>
                </div>
              </el-form-item>
              <template v-if="showArea">
                <table width="98%" height="100" border="1" style="margin-left:2%" cellspacing="0" cellpadding="0">
                  <tr>
                    <th>区县</th>
                    <th>灾害总数</th>
                    <th>滑坡灾害</th>
                    <th>崩塌灾害</th>
                    <th>泥石流灾害</th>
                    <th>地面塌陷灾害</th>
                    <th>地面沉降灾害</th>
                    <th>地裂缝不稳定斜坡灾害</th>
                    <th>其他灾害</th>
                  </tr>
                  <tr v-for="(item,index) in areaList" :key="index">
                    <td v-for="(val,ind) in item" :key="ind">
                      <span>{{val}}</span>
                    </td>
                  </tr>
                </table>
                <div id="mainAreaPic" style="width: 700px; height: 500px;padding-left: 100px;"></div>
                <p style="text-align: center;font-weight: bold;">分区</p>
              </template>
              <el-form-item label="区域统计标题" prop="ssdAreaTitle">
                <el-input v-model="queryParams.ssdAreaTitle" placeholder="请输入标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="描述" prop="ssdDescribe">
                <el-input v-model="queryParams.ssdDescribe" type="textarea" maxlength="300" show-word-limit
                  :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入描述" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleUpload">确定</el-button>
          <el-button @click="cancelUpload">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 商会对话框 -->
    <el-dialog v-model="showOption" width="400px" title="震情趋势" :close-on-click-modal="false">
      <p class="worrning">震情趋势已发生变化，请注意！</p>
      <el-radio v-model="radioOption" label="true" style="margin-left:10px">今日不再提醒</el-radio>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="!radioOption" @click="ok">确定</el-button>
          <el-button @click="cancelOption">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="secondary">
import { listSecond, getSecond, uploadSecond, updateSecond, delSecond, createMonFile, createAreaFile, downTemplate } from "@/api/assess/secondary";
import { setcookieTimeFun, getCookieFun } from "@/utils/popout"
import fileUpload from './FileUpload/index'
import * as echarts from "echarts";

const { proxy } = getCurrentInstance();
const showIcon = ref(false);
const route = useRoute();
const titleOption = ref();
const loading = ref(false);
const showOption = ref(false);
const open = ref(false);
const radioOption = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const id = ref();
const limit = ref(1)
const ssdContent = ref();
const ssdRelation = ref();
const type1 = ref('1');
const type2 = ref('2');
const disabledMonFile = ref(true);
const disabledAreaFile = ref(true);
const mainAreaPic = ref();
const showMon = ref(false);
const showArea = ref(false);
const LineChartMon = ref();
const LineChartArea = ref();
console.log(location.origin,'2222222');
const data = reactive({
  queryParams: {
    ssdImageId: '',
    attach: [],
    mouseAttachment: [],
    areaAttachment: [],
    ssdImageTitle: '',
    ssdDescribe: '',
    ssdMouseFileId: '',
    ssdAreaFileId: '',
    ssdMonthTitle: '',
    ssdAreaTitle: '',
  },
  dataList: [],
  rules: {
    ssdImageId: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    ssdMouseFileId: [{ required: true, message: "按月统计不能为空", trigger: "blur" }],
    ssdAreaFileId: [{ required: true, message: "区域统计不能为空", trigger: "blur" }],
    ssdImageTitle: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    ssdMonthTitle: [{ required: true, message: "按月统计标题不能为空", trigger: "blur" }],
    ssdAreaTitle: [{ required: true, message: "区域统计标题不能为空", trigger: "blur" }],
    ssdDescribe: [{ required: true, message: "描述不能为空", trigger: "blur" }],
  },
  monList:[],
  areaList:[],
})
const { queryParams, dataList, rules,monList,areaList } = toRefs(data);

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 获取列表操作 */
function getList() {
  ssdRelation.value = route.query.id
  id.value = route.query.id;
  // id.value = '123';
  // ssdRelation.value = '123';
  loading.value = true;
  listSecond(id.value).then((response) => {
    dataList.value = response.data.entities;
    titleOption.value = response.data.bsOpinion;
    showIcon.value = Boolean(Number(response.data.bsOpinionStatus));
    loading.value = false;
    ssdContent.value = '';
  });
}
// 打开成果上传开关
function openUpload() {
  reset();
  showMon.value = false;
  showArea.value = false;
  title.value = "上传"
  open.value = true;
  if(ssdContent.value=='地质灾害统计'){
    if(document.getElementById('mainAreaPic')){
    echarts.init(document.getElementById('mainAreaPic')).dispose();
  }
  if(document.getElementById('mainMonPic')){
    echarts.init(document.getElementById('mainMonPic')).dispose();
  }
  }
}

// 重置上传
function reset() {
  queryParams.value = {
    ssdImageId: '',
    attach: [],
    mouseAttachment: [],
    areaAttachment: [],
    ssdImageTitle: '',
    ssdDescribe: '',
    ssdMouseFileId: '',
    ssdAreaFileId: '',
    ssdMonthTitle: '',
    ssdAreaTitle: '',
  }
  proxy.resetForm("secondaryRef");
  monList.value = [];
  areaList.value = [];
}

// 成果上传
function handleUpload() {
  if (ssdContent.value != '地质灾害统计') {
    const fileList = JSON.parse(JSON.stringify(proxy.$refs["imageUpload"].fileList));
    const attachIds = [];
    for (var i = 0; i < fileList.length; i++) {
      attachIds.push(fileList[i].attachId)
    }
    queryParams.value.ssdImageId = attachIds.join(",");
  } else {
    const fileMouse = JSON.parse(JSON.stringify(proxy.$refs["ssdMouseFileRef"].fileList));
    const fileArea = JSON.parse(JSON.stringify(proxy.$refs["ssdAreaFileRef"].fileList));
    queryParams.value.ssdMouseFileId = fileMouse.length != 0 ? JSON.parse(JSON.stringify(proxy.$refs["ssdMouseFileRef"].fileList))[0].attachId : '';
    queryParams.value.ssdAreaFileId = fileArea.length != 0 ? JSON.parse(JSON.stringify(proxy.$refs["ssdAreaFileRef"].fileList))[0].attachId : '';
  }
  proxy.$refs["secondaryRef"].validate(valid => {
    if (valid) {
      if(!monList.value||!areaList.value){
          proxy.$modal.msgWarning ("有图表未生成");
        }
      if (title.value == '上传') {
        let flag = false;
        // 查看是否重复
        if (dataList.value.length == 0) {
          flag = false;
        } else {
          flag = dataList.value.some(item => {
            if (item.ssdContent == ssdContent.value) {
              return true
            }
          });
        }
        flag ? updateUpload() : upload();
      } else if (title.value == '查看') {
        updateSecond(queryParams.value).then(response => {
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function upload() {
  uploadSecond({ ...queryParams.value, ssdContent: ssdContent.value, ssdRelation: ssdRelation.value }).then(response => {
    proxy.$modal.msgSuccess("上传成功");
    open.value = false;
    getList();
  }).catch(() => { });
}
// 是否覆盖
function updateUpload() {
  proxy.$modal.confirm('是否确认覆盖次生灾害隐患评估内容为"' + ssdContent.value + '"的数据项？').then(function () {
    return uploadSecond({ ...queryParams.value, ssdContent: ssdContent.value, ssdRelation: ssdRelation.value });
  }).then(() => {
    proxy.$modal.msgSuccess("上传成功");
    open.value = false;
    getList();
  }).catch(() => { });
}

function getDetail(id) {
  if(document.getElementById('mainAreaPic')){
    echarts.init(document.getElementById('mainAreaPic')).dispose();
  }
  if(document.getElementById('mainMonPic')){
    echarts.init(document.getElementById('mainMonPic')).dispose();
  }
  getSecond(id).then(response => {
    queryParams.value = response.data.secondDisastersById;
    ssdContent.value = response.data.secondDisastersById.ssdContent;
    queryParams.value.mouseAttachment = [response.data.mouseAttachment];
    queryParams.value.areaAttachment = [response.data.areaAttachment];
    queryParams.value.attach =response.data.imageAttachment? [response.data.imageAttachment]:[];
    title.value = "查看"
    open.value = true;
    nextTick(()=>{
      monList.value =response.data.excelByMouth.lists;
      initMon(response.data.excelByMouth);
      areaList.value = response.data.excelByArea.lists;
      initArea(response.data.excelByArea);
    })
    disabledMonFile.value = false;
    disabledAreaFile.value = false;
    showMon.value = true;
    showArea.value = true;
  })
}

/** 查看方法*/
function handleDetil(row) {
  title.value = '查看';
  reset();
  if(document.getElementById('mainMonPic')){
      LineChartMon.value.dispose();
    }
  if(document.getElementById('mainAreaPic')){
    LineChartArea.value.dispose();
  }
  showMon.value = false;
  showArea.value = false;
  getDetail(row.ssdId)
}

// 取消成果上传
function cancelUpload() {
  reset();
  showMon.value = false;
  showArea.value = false;
  open.value = false;
  if(document.getElementById('mainMonPic')){
      LineChartMon.value.dispose();
    }
  if(document.getElementById('mainAreaPic')){
    LineChartArea.value.dispose();
  }
}

/** 删除按钮操作 */
function handledel(row) {
  const id = row.ssdId;
  proxy.$modal.confirm('是否确认删除' + row.ssdContent + '的数据项？').then(function () {
    return delSecond(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

function delFile(val) {
  if (val.type == '1') {
    queryParams.value.ssdMouseFileId = '';
    disabledMonFile.value = true;
    showMon.value = false;
    if(document.getElementById('mainMonPic')){
      LineChartMon.value.dispose();
    }
  } else {
    queryParams.value.ssdAreaFileId = '';
    disabledAreaFile.value = true;
    showArea.value = false;
    if(document.getElementById('mainAreaPic')){
      LineChartArea.value.dispose();
    }
  }
}

function uploadFile(val) {
  if (val.type == '1') {
    queryParams.value.ssdMouseFileId = val.fileList;
    disabledMonFile.value = false;
  } else {
    queryParams.value.ssdAreaFileId = val.fileList;
    disabledAreaFile.value = false;
  }
}

function initMon(data) {
  // 基于准备好的dom，初始化echarts实例
  console.log(document.getElementById('mainMonPic'), '获取id');
  // document.getElementById("mainMonPic").removeAttribute('_echarts_instance_');
  LineChartMon.value = echarts.init(document.getElementById('mainMonPic'));
  // 指定图表的配置项和数据
  var option = {
    xAxis: {
      type: 'category',
      data: data.mouth,
      axisLabel: {
        interval: 0, // 调整数值即可调整坐标显示间隔
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '数量',
        data: data.sum,
        type: 'bar',
      },
    ]
  };
  // 使用刚指定的配置项和数据显示图表。 给一个延时
  LineChartMon.value.clear();
  option && LineChartMon.value.setOption(option);
}

function initArea(data) {
  // 基于准备好的dom，初始化echarts实例
  // document.getElementById("mainAreaPic").removeAttribute('_echarts_instance_');
  LineChartArea.value = echarts.init(document.getElementById('mainAreaPic'));
  // 指定图表的配置项和数据
  var option = {
    xAxis: {
      type: 'category',
      data: data.areaList
    },
    yAxis: {
      type: 'value',
      name: '数量/起'
    },
    series: [
      {
        data: data.countList,
        type: 'bar',
      }
    ]
  };
  // 使用刚指定的配置项和数据显示图表。
  LineChartArea.value.clear();
  option && LineChartArea.value.setOption(option); 
}
// 生成按月的图表
function createExcleMon() {
  createMonFile(queryParams.value.ssdMouseFileId).then(res => {
    console.log(res.data);
    showMon.value = true;
    nextTick(() => {
      monList.value = res.data.lists;
      initMon(res.data);
    })
  })
}

// 生成区域的图表
function createExcleArea() {
  createAreaFile(queryParams.value.ssdAreaFileId).then(res => {
    console.log(res.data);
    showArea.value = true;
    nextTick(() => {
      areaList.value = res.data.lists;
      initArea(res.data);
    })
  })
}

// 模板下载
function importTemplate(name) {
  proxy.download("/fxfzaqbz/data/downloadExcel", {
    fileName:name
  }, name);
};


// 评估
function handleAssess() {

}

// 下载
function handleDownload() {

}

// 提交
function handleSubmit() {

}

// 监听单选按钮
watch(showIcon, (val) => {
  showOption.value = val;
  if (showOption.value) {
    getTimeSetCookieFun(`secondaryCookie${route.query.id}`)
  }
})

// 获取日期时间
function getTimeSetCookieFun(name) {
  var day = getCookieFun(name) == '' ? '' : getCookieFun(name);
  if (day == '') {
    // console.log('没有cookie,说明过期或者还没有存')
    showOption.value = true;
  } else {
    var newTime = new Date().getDate();
    if (newTime > day) {
      // console.log('我是新的一天,我要弹窗')
      showOption.value = true;
    } else {
      showOption.value = false;
    }
  }
}
// 取消商会意见
function cancelOption() {
  showOption.value = false;
}
// // 确认不再提示
function ok() {
  var newTime = new Date().getDate();
  setcookieTimeFun(`secondaryCookie${route.query.id}`, newTime, 1);
  showOption.value = false;
}

getList();
</script>
<style lang="scss" scoped>
.container {
  margin: 0px auto;
  height: 100%;
  width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;

  .worrning {
    width: 340px;
    height: 110px;
    color: #3d4a5d;
    font-size: 18px;
    line-height: 26px;
    background: #f5f9fe;
    margin: 30px auto 10px;
    padding: 15px;
  }

  .header {
    padding: 10px 0px;

    .title {
      font-size: 18px;
      font-weight: bold;
    }

    div {
      height: 60px;
      line-height: 60px;
      margin-top: 10px;

      &.icon {
        padding: 0 20px;
        background: #f5f9fe;
      }
    }
  }
}
tr{
  font-size: 12px;
  td{
    text-align: center;
  }
}
</style>
